package controllers;

import java.util.Calendar;
import java.util.List;

import models.Adpo;
import models.Advert;
import service.AdpoService;
import service.AdvertService;

@CRUD.For(Advert.class)
public class AdvertAction extends CRUD{

	/**
	 * 查询相关广告位的广告信息的方法
	 * 
	 * @param id  广告位id
	 */
	public static void list(Long id){
		List<Advert> adverts = AdvertService.findByAdpId(id);
		render(adverts,id);
	}
	
	/**
	 * 跳转向添加页面的方法
	 * 
	 * @param id  广告位id
	 */
	public static void blank(Long id){
		System.out.println(id);
		render(id);
	}
	
	/**
	 * 添加广告信息的方法
	 * 
	 * @param advert 广告对象
	 * @param adpId  广告位id
	 */
	public static void create(Advert advert,Long adpId){
		advert.adpo = AdpoService.findById(adpId);
		advert.advDate = Calendar.getInstance().getTime();
		try {
			AdvertService.add(advert);
			flash.success("添加成功");
			list(adpId);
		} catch (Exception e) {
			System.out.println("#################AdvertAction.create() Exception######################");
			flash.success("添加失败");
			blank(adpId);
		}
	}
	
	/**
	 * 跳转向修改页面的方法
	 * 
	 * @param advId  广告id
	 */
	public static void show(Long advId){
		Advert advert = AdvertService.findById(advId);
		List<Adpo> adpos = AdpoService.findAll();
		render(advert,adpos);
	}
	
	/**
	 * 修改广告信息的方法
	 * 
	 * @param advert 广告信息对象
	 * @param id     广告位id
	 */
	public static void save(Advert advert,Long adpId){
		advert.adpo = AdpoService.findById(adpId);
		try {
			AdvertService.update(advert);
			flash.success("修改成功");
			list(adpId);
		} catch (Exception e) {
			System.out.println("#################AdvertAction.save() Exception######################");
			flash.success("修改失败");
			show(advert.id);
		}
	}
	
	/**
	 * 删除广告信息的方法
	 * 
	 * @param id  广告id
	 */
	public static void delete(Long advId,Long id){
		try {
			AdvertService.delete(advId);
			flash.success("删除成功");
			list(id);
		} catch (Exception e) {
			System.out.println("#################AdvertAction.delete() Exception######################");
			flash.success("删除失败");
			list(id);
		}

	}
}
